define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'qingdongwms/product/goods/index' + location.search,
                    add_url: 'qingdongwms/product/goods/add',
                    edit_url: 'qingdongwms/product/goods/edit',
                    detail_url: 'qingdongwms/product/goods/detail',
                    multi_url: 'qingdongwms/product/goods/multi',
                    import_url: 'qingdongwms/product/goods/import',
                    table: 'qingdongwms_goods',
                }
            });
            var isselect=false;
            var pselect = true;
            var q = {};
            location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);
            if (q.isselect == 1) {
                isselect= true;
                pselect = false;
            }
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {
                            field : 'name', title : '商品名称', operate : 'like', fixedColumns : true, formatter : function (value, row, index) {
                                return "<a href='javascript:void(0);' data-id='" + row.id + "'  class='show-goods' >" + value + "</a>";
                            }
                        },
                        {
                            field: 'type.name', title: '商品分类', operate: false
                        },
                        {field: 'type_id', title: __('商品分类'), searchList: $.getJSON("qingdongwms/product/goods/get_product_type"),visible:false},
                        {field: 'cost_price', title: __('采购价'), operate: 'LIKE'},
                        {field: 'unit', title: __('单位'), operate: 'LIKE'},

                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate2', title: __('Operate'),visible:isselect, events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    Fast.api.close(row);
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        },
                        {
                            field: 'operate', title: __('Operate'),table: table,visible:pselect,
                            events: Table.api.events.operate, formatter: Table.api.formatter.buttons,
                            buttons: [

                                {
                                    name: 'edit',
                                    text: __('编辑'),
                                    title: __('编辑'),
                                    extend:'data-area=["90%","90%"]',
                                    classname: 'records btn-dialog',
                                    url: 'qingdongwms/product/goods/edit',
                                },
                                {
                                    name: 'detail',
                                    text: __('详情'),
                                    title: __('详情'),
                                    extend:'data-area=["95%","95%"]',
                                    classname: 'records btn-dialog',
                                    url: 'qingdongwms/product/goods/detail',
                                },

                            ]
                        },
                    ]
                ],
                search:false,
                //启用普通表单搜索
                commonSearch      : true,
                searchFormVisible:true,
                showSearch         : true,
                pageSize           : 10,
                onLoadSuccess: function () {
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-add").data("area", ["90%", "90%"]);
                    $(".btn-edit").data("area", ["90%", "90%"]);
                }
            });
            $(document).on('click', '.show-goods', function (data) {
                var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    refresh:true,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果

                    },
                    end:function (){
                        $('.btn-refresh').trigger('click');
                    }
                };
                Fast.api.open($.fn.bootstrapTable.defaults.extend.detail_url + "?ids=" + $(this).data('id'), '商品详情', options);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'qingdongwms/product/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'qingdongwms/product/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'qingdongwms/product/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {

            $(document).on('change','input[name="row[specs_type]"]',function (){
                var specs = $(this).val();
                if(specs == 1){
                    $('.specesinfo').show();
                    $('.goodsinfo').hide();
                }else{
                    $('.specesinfo').hide();
                    $('.goodsinfo').show();
                }
            });
            Controller.api.bindevent();
        },
        edit: function () {
            //后续操作
            var ids = $('#ids').val();
            var specs_id=$("#specs_id").val();
            var price=$('#c-price').val();

            $.post('qingdongwms/product/goods/get_specs_detail',{specs_id:specs_id,ids:ids},function (data){
                if(data.code == 1){
                    var result=[];
                    var specslist='';
                    $.each(data.data,function (index,params){
                        params.type=params.name;
                        params.name='['+params.name+']';
                        params.price=price;
                        params.remarks="";
                        params.avatar="";
                        params.index=index;

                        result.push(params);
                        var dataparams=JSON.stringify(params);
                        if(params.check && params.check == 1){
                            specslist+='<a class="label label-default  label-specs label-info" data-params=\''+dataparams+'\' data-id="'+index+'" data-show="1" checked="checked">'+params.name+'</a> ';

                        }else{
                            specslist+='<a class="label label-default  label-specs" data-params=\''+dataparams+'\' data-id="'+index+'" data-show="0" >'+params.name+'</a> ';

                        }
                    });
                    $('#specslist').html(specslist);

                }
            },'json');
            $(document).on('change','input[name="row[specs_type]"]',function (){
                var specs = $(this).val();
                if(specs == 1){
                    $('.specesinfo').show();
                    $('.goodsinfo').hide();
                }else{
                    $('.specesinfo').hide();
                    $('.goodsinfo').show();
                }
            });
            Controller.api.bindevent();
        },
        import: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            // 初始化表格参数配置

            Table.api.init({});
            var id = $('#ids').val();
            //产品信息
            var table1 = $("#operation_product");
            // 初始化表格
            table1.bootstrapTable({
                url          : 'qingdongwms/product/goods/get_product?goods_id=' +id,
                pk           : 'id',
                sortName     : 'id',
                toolbar: '#toolbar_product',
                operate      : false,
                commonSearch : false,
                search       : false,
                visible      : false,
                showColumns  : false,
                showExport   : false,
                showToggle   : false,
                columns      : [
                    [
                        {
                            field : 'producttype.name', title : '产品分类'
                        },
                        {
                            field : 'name', title : '产品名称', operate : 'like', fixedColumns : true, formatter : function (value, row, index) {
                                return "<a href='javascript:void(0);' class='btn-dialog' " +
                                    "data-url='qingdongwms/product/product/detail/ids/"+row.id+"' data-shade='0.3' data-title='产品详情' >" + value + "</a>";
                            }
                        },
                        {field : 'num', title : '产品编码', operate : 'like'},
                        {field: 'img', title: '产品图片', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field : 'unit', title : '产品单位', operate : false},
                        {field : 'price', title : '零售价', operate : false},
                        {field : 'wholesale', title : '批发价', operate : false},
                        {field : 'cost_price', title : '采购价', operate : false},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table1);


            //编辑
            $(document).on('click','.btn-edit',function () {
                var id=$('#ids').val();
                Fast.api.open("qingdongwms/product/goods/edit?ids="+id, "编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    'area':['90%','90%'],
                    callback:function () {
                        location.reload()
                    }
                });

            });
            $(document).on('click', ".btn-del", function () {//删除
                var id = $('#ids').val();
                Layer.confirm('确定删除当前商品吗？', {
                    btn   : ['确定', '取消'],
                    title : '提示',
                }, function (index, layero) {
                    Fast.api.ajax("qingdongwms/product/goods/del?ids=" + id, function (data, ret) {
                        if (ret.code == 1) {
                            Layer.close(index);
                            parent.location.reload();
                        }
                    }, function (data, ret) {
                    });

                });
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.plupload($("form"));
                });

                $("#specs_id").data("eSelect", function(){
                    //后续操作
                    var specs_id=$("#specs_id").val();
                    var price=$('#c-price').val();
                    $.post('qingdongwms/product/goods/get_specs_detail',{specs_id:specs_id},function (data){
                        if(data.code == 1){
                            var result=[];
                            var specslist='';
                            $.each(data.data,function (index,params){
                                params.type=params.name;
                                params.name='['+params.name+']';
                                params.price=price;
                                params.remarks="";
                                params.avatar="";
                                params.index=index;

                                result.push(params);
                                var dataparams=JSON.stringify(params);
                                specslist+='<a class="label label-default  label-specs" data-params=\''+dataparams+'\' data-id="'+index+'" data-show="0" >'+params.name+'</a> ';
                            });
                            $('#specslist').html(specslist);

                        }
                    },'json');
                });
                $(document).on('click','.label-specs',function (){
                    var is_show=$(this).attr('data-show');
                    var product=$('textarea[name="row[product]"]').val();

                    if(is_show == 1){
                        $(this).attr({'data-show':0});
                        $(this).removeClass('label-info');

                        var id=$(this).data('id');
                        product=JSON.parse(product);
                        var result=[];
                        $.each(product,function (index,params){
                            if(params.index != id){
                                result.push(params);
                            }
                        });
                        result=JSON.stringify(result);
                        $('textarea[name="row[product]"]').val(result);
                        $(".fieldlist").trigger("fa.event.refreshfieldlist");
                        $('textarea[name="row[product]"]').trigger("fa.event.refreshfieldlist");
                    }else{
                        $(this).addClass('label-info');
                        $(this).attr({'data-show':1});

                        var params=$(this).data('params');
                        product=JSON.parse(product);
                        product.push(params);

                        var res=JSON.stringify(product);
                        $('textarea[name="row[product]"]').val(res);
                        $(".fieldlist").trigger("fa.event.refreshfieldlist");
                        $('textarea[name="row[product]"]').trigger("fa.event.refreshfieldlist");
                    }
                });
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});